package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.Utils.ValidateCodeUtils;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author Mylinja 2021-12-20 星期一 11:18
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        log.info("发送验证码...");

        //1 获取用户手机号
        String phone = user.getPhone();
        if (Strings.isEmpty(phone)) {
            return R.error("手机号不能为空");
        }
        //String[] phoneNumbers = {phone};

        //2 获取随机生成的验证码
        String code = ValidateCodeUtils.generateValidateCode4String(4);
        //String[] param = {code};

        //3 调用短信发送工具类
        //TencentSmsUtils.sendMessage(phoneNumbers, param);

        //4 把code验证码存到session中
        session.setAttribute(phone, code);

        log.info("手机号为：{}，验证码为：{}", phone, code);
        return R.success("验证码已发送");
    }

    @PostMapping("/login")
    public R<String> login(@RequestBody Map<String, String> map, HttpSession session) {
        log.info("用户开始登录...");

        //1 获取前端传递的手机号和验证码
        String phoneNumber = map.get("phone");
        String codeNumber = map.get("code");

        //2 从Session中获取到手机号对应的正确的验证码
        String attribute = (String) session.getAttribute(phoneNumber);

        //3 进行验证码的比对 , 如果比对失败, 直接返回错误信息
        if (attribute == null || !attribute.equals(codeNumber)) {
            return R.error("登录失败");
        }

        //4 如果比对成功, 需要根据手机号查询当前用户, 如果用户不存在, 则自动注册一个新用户
        LambdaQueryWrapper<User> query = new LambdaQueryWrapper<>();
        query.eq(User::getPhone, phoneNumber);
        User user = userService.getOne(query);
        if (user == null) {
            // 如果用户不存在
            user = new User();
            user.setPhone(phoneNumber);
            user.setStatus(1);
            userService.save(user);
        }

        //5 将登录用户的ID存储Session中
        log.info("user用户已保存，id为：{}", user.getId());
        session.setAttribute("user", user.getId());
        return R.success("登录成功");
    }

    /**
     * 用户登出业务
     * 清楚session域对象中的员工即可
     *
     * @return 返回成功即可
     */
    @PostMapping("/loginout")
    public R<Object> logout(HttpSession session) {
        long userId = (long) session.getAttribute("user");
        log.info("后台系统员工退出，员工id为：{}", userId);
        session.invalidate();
        return R.success(null);
    }
}
